import { Injectable } from '@nestjs/common'
import { Cart } from '../entities/cart.entity'
import { InjectRepository } from '@nestjs/typeorm'
import { In, Repository } from 'typeorm'
import { Goods } from '../entities/goods.entity'

@Injectable()
export class CartService {
  constructor(
    @InjectRepository(Cart) private readonly cartRepository: Repository<Cart>,
    @InjectRepository(Goods) private readonly goodsRepository: Repository<Goods>,
  ) {}

  /**
   * 添加购物车
   * @param uid
   * @param gid
   * @param num
   */
  async save({ uid, gid, num }: Cart) {
    try {
      const cart = await this.cartRepository.findOne({ where: { uid, gid } })
      // 判断购物车是否有相同的商品
      if (cart) {
        // 数据库中有相同商品【增加数量】
        await this.cartRepository.update(cart.id, { num: num + cart.num })
      } else {
        // 没有则添加到购物车
        await this.cartRepository.save({ uid, gid, num })
      }
      return '添加成功'
    } catch (e) {
      return '添加失败'
    }
  }

  /**
   * 查询购物车记录
   * @param uid
   */
  async queryAll(uid) {
    // 方式一：性能低
    // 从cart表中查询【用户】的购物车记录
    /*
    const carts = await this.cartRepository.find({
      where: { uid },
      select: ['id', 'num', 'gid'],
    })
    const array = []
    for (const item of carts) {
      const goods = await this.goodsRepository.findOne({ where: { id: item.gid } })
      array.push({ id: item.id, num: item.num, goods })
    }
    return array
    */

    // 方式二
    // 从cart表中查询【用户】的购物车记录
    const carts = await this.cartRepository.find({
      where: { uid },
      select: ['id', 'num', 'gid'],
    })
    // 取出【用户】的购物车记录中商品的id
    const gids = carts.map((item) => item.gid)
    // 查询商品的信息
    const goods = await this.goodsRepository.find({ where: { id: In(gids) } })
    return goods.map((item) => {
      // 匹配商品id和购物车记录中id一致的数据
      const cart = carts.filter((el) => el.gid === item.id)
      return { ...cart[0], goods: item }
    })
  }

  /**
   * 修改
   * @param id
   * @param num
   */
  async edit({ id, num }) {
    const { affected } = await this.cartRepository.update(id, { num })
    return affected ? '修改成功' : '修改失败'
  }

  async del(id) {
    const { affected } = await this.cartRepository.delete(id)
    return affected ? '删除成功' : '删除失败'
  }
}
